package com.fuelindustries.ant.jsfl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.fuelindustries.ant.FuelAntVariables;
import com.fuelindustries.ant.utils.OSUtils;

public class CloseFlash 
{
	private String __jsfl;
	private String __flashpath;
	
	
	public CloseFlash()
	{
	}
	
	public void close( String flashpath )
	{
		__flashpath = flashpath;
		
		try
		{
			createJSFL();
			runJSFL();
			cleanup();
		}
		catch( Exception e )
		{
			System.out.println( e.getMessage() );
		}
	}
	
	private void createJSFL() throws IOException
	{
		__jsfl = FuelAntVariables.BASE_DIR + FuelAntVariables.TEMP_DIR + File.separator + FuelAntVariables.CLOSE_JSFL;
		FileWriter writer = new FileWriter( __jsfl );
		BufferedWriter buffer = new BufferedWriter( writer );
		buffer.write("fl.quit( false );");
		buffer.newLine();
		buffer.close();
	}
	
	private void runJSFL() throws IOException, InterruptedException
	{
		String[] command = new String[]{};
		if( OSUtils.isWindows() )
		{
			command = new String[]{ __flashpath, __jsfl };
		}
		else
		{
			command = new String[]{ "osascript", "-e", "tell app \"" + __flashpath + "\" to open posix file \""+ __jsfl +"\"" };
		}
		
		Process result = Runtime.getRuntime().exec( command );
        result.waitFor();

        result.destroy();
	}
	
	private void cleanup()
	{
		File file = new File( __jsfl );
		while( file.exists() )
		{
			file.delete();
		}
	}
}
